'use client';

import React, { useState, useCallback, useRef } from 'react';
import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { Progress } from '@/components/ui/progress';
import { Alert, AlertDescription } from '@/components/ui/alert';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { 
  Upload, 
  FileText, 
  CheckCircle, 
  XCircle, 
  AlertTriangle, 
  Download,
  RefreshCw,
  Info,
  X
} from 'lucide-react';
import { toast } from '@/hooks/use-toast';

interface ImportResult {
  success: boolean;
  totalRows: number;
  successRows: number;
  errorRows: number;
  skippedRows: number;
  records: ImportedRecord[];
  summary: {
    duplicateObjectNumbers: string[];
    missingRequiredFields: { row: number; fields: string[] }[];
    invalidDataTypes: { row: number; field: string; value: any; expectedType: string }[];
    skippedInvalidRows: { row: number; reason: string }[];
  };
}

interface ImportedRecord {
  deviceClass: string;
  objectNumber: string;
  objectDescription: string;
  namingData: Record<string, any>;
  positionData: Record<string, any>;
  paramsData: Record<string, any>;
  errors: string[];
  warnings: string[];
}

interface DataImportDialogProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  specialty: string;
  objectCategory: string;
  userRole: string;
  classificationCode?: string;
}

type ImportStep = 'select' | 'upload' | 'validate' | 'results' | 'success';

interface ValidationChoice {
  action: 'retry' | 'import_valid' | 'import_all';
  label: string;
  description: string;
  color: string;
}

export function DataImportDialog({
  open,
  onOpenChange,
  specialty,
  objectCategory,
  userRole,
  classificationCode
}: DataImportDialogProps) {
  
  // 当对话框关闭时重置状态
  const handleOpenChange = (newOpen: boolean) => {
    if (!newOpen) {
      resetDialog();
    }
    onOpenChange(newOpen);
  };
  const [currentStep, setCurrentStep] = useState<ImportStep>('select');
  const [selectedFile, setSelectedFile] = useState<File | null>(null);
  const [uploadProgress, setUploadProgress] = useState(0);
  const [importResult, setImportResult] = useState<ImportResult | null>(null);
  const [loading, setLoading] = useState(false);
  const [dragActive, setDragActive] = useState(false);
  const [isCancelled, setIsCancelled] = useState(false);
  const fileInputRef = useRef<HTMLInputElement>(null);

  const handleFileSelect = useCallback((file: File) => {
    if (!file.name.endsWith('.xlsx') && !file.name.endsWith('.xls')) {
      toast({
        title: '文件格式错误',
        description: '请选择Excel文件（.xlsx或.xls格式）',
        variant: 'destructive'
      });
      return;
    }

    setSelectedFile(file);
    setCurrentStep('upload');
  }, []);

  const handleDrag = useCallback((e: React.DragEvent) => {
    e.preventDefault();
    e.stopPropagation();
    if (e.type === 'dragenter' || e.type === 'dragover') {
      setDragActive(true);
    } else if (e.type === 'dragleave') {
      setDragActive(false);
    }
  }, []);

  const handleDrop = useCallback((e: React.DragEvent) => {
    e.preventDefault();
    e.stopPropagation();
    setDragActive(false);

    if (e.dataTransfer.files && e.dataTransfer.files[0]) {
      handleFileSelect(e.dataTransfer.files[0]);
    }
  }, [handleFileSelect]);

  const handleFileInputChange = useCallback((e: React.ChangeEvent<HTMLInputElement>) => {
    if (e.target.files && e.target.files[0]) {
      handleFileSelect(e.target.files[0]);
    }
  }, [handleFileSelect]);

  const validateData = async () => {
    console.log('=== 开始数据验证 ===');
    console.log('选中文件:', selectedFile);
    console.log('专业:', specialty);
    console.log('对象类:', objectCategory);
    console.log('分类代码:', classificationCode);
    
    if (!selectedFile) {
      console.log('没有选中文件');
      return;
    }

    // 重置取消状态
    setIsCancelled(false);

    // 校验文件名是否与选择的对象类匹配
    // 新格式：专业-对象类.xlsx（允许包含额外后缀如 (1), (2) 等）
    const fileName = selectedFile.name.replace(/\.xlsx?$/i, ''); // 移除扩展名
    
    // 灵活校验：文件名应以"专业-对象类"开头
    const expectedPattern = `${specialty}-${objectCategory}`;
    
    console.log('文件名:', fileName);
    console.log('期望格式:', expectedPattern);
    
    // 检查文件名是否以期望格式开头（允许后面有额外内容如 " (1)", " (2)" 等）
    if (!fileName.startsWith(expectedPattern)) {
      console.log('文件名不匹配');
      toast({
        title: '文件名不匹配',
        description: `Excel文件名应以：${expectedPattern} 开头`,
        variant: 'destructive'
      });
      return;
    }
    
    console.log('文件名验证通过，开始数据验证');
    
    setLoading(true);
    setCurrentStep('validate');
    setUploadProgress(0);

    try {
      // 模拟上传进度
      const progressInterval = setInterval(() => {
        setUploadProgress(prev => {
          if (prev >= 90) {
            clearInterval(progressInterval);
            return prev;
          }
          return prev + 10;
        });
      }, 200);

      console.log('读取文件内容...');
      const buffer = await selectedFile.arrayBuffer();
      console.log('文件读取完成，大小:', buffer.byteLength);
      
      // 检查是否已取消
      if (isCancelled) {
        console.log('验证已取消');
        return;
      }
      
      // 使用API调用而不是直接调用服务
      const formData = new FormData();
      formData.append('file', selectedFile);
      formData.append('specialty', specialty);
      formData.append('objectCategory', objectCategory);
      formData.append('validateOnly', 'true');
      if (classificationCode) {
        formData.append('classificationCode', classificationCode);
      }

      console.log('发送验证请求到 /api/data-import');
      console.log('请求参数:', {
        fileName: selectedFile.name,
        specialty,
        objectCategory,
        classificationCode,
        validateOnly: true
      });

      const response = await fetch('/api/data-import', {
        method: 'POST',
        body: formData
      });
      
      console.log('API响应状态:', response.status, response.statusText);

      // 检查是否已取消
      if (isCancelled) {
        console.log('验证已取消');
        return;
      }

      if (!response.ok) {
        const errorText = await response.text();
        console.error('API响应错误:', errorText);
        throw new Error(`验证失败: ${response.statusText} - ${errorText}`);
      }

      console.log('解析API响应...');
      const data = await response.json();
      console.log('API响应数据:', data);
      
      if (!data.success) {
        console.error('验证服务返回错误:', data.error);
        throw new Error(data.error);
      }

      const result = data.data;
      console.log('验证结果:', result);

      clearInterval(progressInterval);
      setUploadProgress(100);
      setImportResult(result);
      setCurrentStep('results');

      const message = result.skippedRows > 0 
        ? `总计 ${result.totalRows} 条记录，${result.successRows} 条通过验证，${result.errorRows} 条存在错误，${result.skippedRows} 条无效行已跳过`
        : `总计 ${result.totalRows} 条记录，${result.successRows} 条通过验证，${result.errorRows} 条存在错误`;
      
      toast({
        title: '数据验证完成',
        description: message,
      });

    } catch (error) {
      console.error('验证过程出错:', error);
      toast({
        title: '验证失败',
        description: error instanceof Error ? error.message : '未知错误',
        variant: 'destructive'
      });
      setCurrentStep('upload');
    } finally {
      setLoading(false);
    }
  };

  const handleImportChoice = async (choice: 'retry' | 'import_valid' | 'import_all') => {
    if (!selectedFile || !importResult) return;

    setLoading(true);

    try {
      if (choice === 'retry') {
        // 重新选择文件
        setCurrentStep('select');
        setSelectedFile(null);
        setImportResult(null);
        setLoading(false);
        return;
      } 
      
      // 执行实际导入
      console.log('开始执行导入，选择:', choice);
      
      const formData = new FormData();
      formData.append('file', selectedFile);
      formData.append('specialty', specialty);
      formData.append('objectCategory', objectCategory);
      formData.append('validateOnly', 'false');
      formData.append('skipDuplicates', (choice === 'import_valid').toString());
      if (classificationCode) {
        formData.append('classificationCode', classificationCode);
      }

      console.log('发送导入请求到 /api/data-import');
      
      const response = await fetch('/api/data-import', {
        method: 'POST',
        body: formData
      });

      console.log('导入响应状态:', response.status);

      if (!response.ok) {
        const errorText = await response.text();
        console.error('导入响应错误:', errorText);
        throw new Error(`导入失败: ${response.statusText} - ${errorText}`);
      }

      const data = await response.json();
      console.log('导入响应数据:', data);
      
      if (!data.success) {
        throw new Error(data.error);
      }

      const finalResult = data.data;
      setImportResult(finalResult);
      setCurrentStep('success');

      toast({
        title: '数据导入完成',
        description: `成功导入 ${finalResult.successRows} 条记录到 ${specialty}-${objectCategory}`,
      });

    } catch (error) {
      console.error('导入处理错误:', error);
      toast({
        title: '导入失败',
        description: error instanceof Error ? error.message : '未知错误',
        variant: 'destructive'
      });
    } finally {
      setLoading(false);
    }
  };

  const resetDialog = () => {
    setCurrentStep('select');
    setSelectedFile(null);
    setImportResult(null);
    setUploadProgress(0);
    setLoading(false);
    setIsCancelled(false);
    if (fileInputRef.current) {
      fileInputRef.current.value = '';
    }
  };

  const handleCancel = () => {
    setIsCancelled(true);
    setLoading(false);
    resetDialog();
    handleOpenChange(false);
  };

  const validationChoices: ValidationChoice[] = [
    {
      action: 'retry',
      label: '修改后再上传',
      description: '根据验证结果修改Excel文件后重新上传',
      color: 'blue'
    },
    {
      action: 'import_valid',
      label: '仅导入通过验证的数据',
      description: `导入 ${importResult?.successRows || 0} 条验证通过的记录，跳过错误数据`,
      color: 'green'
    },
    {
      action: 'import_all',
      label: '导入全部数据',
      description: '导入所有数据，包括存在警告的记录（不推荐）',
      color: 'orange'
    }
  ];

  return (
    <Dialog open={open} onOpenChange={handleOpenChange}>
      <DialogContent className="max-w-4xl max-h-[90vh] overflow-auto">
        <DialogHeader>
          <DialogTitle className="flex items-center gap-2">
            <Upload className="h-5 w-5" />
            数据导入 - {specialty} - {objectCategory}
          </DialogTitle>
        </DialogHeader>

        <div className="space-y-6">
          {/* 进度指示器 */}
          <div className="flex items-center justify-between">
            {[
              { key: 'select', label: '选择文件', icon: FileText },
              { key: 'upload', label: '上传文件', icon: Upload },
              { key: 'validate', label: '数据验证', icon: RefreshCw },
              { key: 'results', label: '验证结果', icon: CheckCircle },
              { key: 'success', label: '导入完成', icon: CheckCircle }
            ].map((step, index) => {
              const isActive = currentStep === step.key;
              const isCompleted = ['select', 'upload', 'validate', 'results'].indexOf(currentStep) > index;
              const Icon = step.icon;
              
              return (
                <div key={step.key} className="flex items-center">
                  <div className={`flex items-center justify-center w-8 h-8 rounded-full ${
                    isCompleted ? 'bg-green-500 text-white' :
                    isActive ? 'bg-blue-500 text-white' :
                    'bg-gray-200 text-gray-500'
                  }`}>
                    <Icon className="h-4 w-4" />
                  </div>
                  <span className={`ml-2 text-sm ${
                    isActive ? 'font-medium text-blue-600' :
                    isCompleted ? 'text-green-600' :
                    'text-gray-500'
                  }`}>
                    {step.label}
                  </span>
                  {index < 4 && <div className="w-8 h-px bg-gray-300 mx-4" />}
                </div>
              );
            })}
          </div>

          {/* 文件选择步骤 */}
          {currentStep === 'select' && (
            <Card>
              <CardHeader>
                <CardTitle>选择Excel文件</CardTitle>
              </CardHeader>
              <CardContent>
                <div
                  className={`border-2 border-dashed rounded-lg p-8 text-center cursor-pointer transition-colors ${
                    dragActive ? 'border-blue-500 bg-blue-50' : 'border-gray-300 hover:border-gray-400'
                  }`}
                  onDragEnter={handleDrag}
                  onDragLeave={handleDrag}
                  onDragOver={handleDrag}
                  onDrop={handleDrop}
                  onClick={() => fileInputRef.current?.click()}
                >
                  <Upload className="h-12 w-12 mx-auto text-gray-400 mb-4" />
                  <p className="text-lg font-medium text-gray-700">
                    拖拽Excel文件到此处，或点击选择文件
                  </p>
                  <p className="text-sm text-gray-500 mt-2">
                    支持 .xlsx 和 .xls 格式
                  </p>
                  
                  <input
                    ref={fileInputRef}
                    type="file"
                    accept=".xlsx,.xls"
                    onChange={handleFileInputChange}
                    className="hidden"
                  />
                </div>

                <Alert className="mt-4">
                  <AlertTriangle className="h-4 w-4" />
                  <AlertDescription>
                    请确保Excel文件是基于系统导出的模板填写的，并且包含"数据录入"工作表。
                    文件命名建议格式：{specialty}-{objectCategory}.xlsx
                  </AlertDescription>
                </Alert>

                <div className="flex justify-end mt-4">
                  <Button variant="outline" onClick={handleCancel}>
                    取消
                  </Button>
                </div>
              </CardContent>
            </Card>
          )}

          {/* 文件上传步骤 */}
          {currentStep === 'upload' && selectedFile && (
            <Card>
              <CardHeader>
                <CardTitle>确认上传文件</CardTitle>
              </CardHeader>
              <CardContent className="space-y-4">
                <div className="flex items-center gap-4 p-4 bg-gray-50 rounded-lg">
                  <FileText className="h-8 w-8 text-blue-500" />
                  <div className="flex-1">
                    <p className="font-medium">{selectedFile.name}</p>
                    <p className="text-sm text-gray-500">
                      大小: {(selectedFile.size / 1024).toFixed(1)} KB
                    </p>
                  </div>
                </div>

                <div className="grid grid-cols-2 gap-4 text-sm">
                  <div>
                    <span className="font-medium">目标专业:</span> {specialty}
                  </div>
                  <div>
                    <span className="font-medium">设备分类:</span> {objectCategory}
                  </div>
                  {classificationCode && (
                    <div>
                      <span className="font-medium">分类代码:</span> {classificationCode}
                    </div>
                  )}
                  <div>
                    <span className="font-medium">用户角色:</span> {userRole}
                  </div>
                </div>

                <div className="flex gap-3">
                  <Button 
                    onClick={validateData} 
                    disabled={loading}
                    className="flex-1"
                  >
                    {loading ? (
                      <>
                        <RefreshCw className="h-4 w-4 mr-2 animate-spin" />
                        正在验证...
                      </>
                    ) : (
                      <>
                        <CheckCircle className="h-4 w-4 mr-2" />
                        开始数据验证
                      </>
                    )}
                  </Button>
                  <Button variant="outline" onClick={() => setCurrentStep('select')}>
                    重新选择
                  </Button>
                  <Button variant="outline" onClick={handleCancel}>
                    取消
                  </Button>
                </div>
              </CardContent>
            </Card>
          )}

          {/* 验证进度步骤 */}
          {currentStep === 'validate' && (
            <Card>
              <CardHeader>
                <CardTitle>数据验证中</CardTitle>
              </CardHeader>
              <CardContent className="space-y-4">
                <div className="text-center">
                  <RefreshCw className="h-12 w-12 mx-auto text-blue-500 animate-spin mb-4" />
                  <p className="text-lg font-medium">正在解析和验证Excel数据...</p>
                  <p className="text-sm text-gray-500 mt-2">
                    系统正在检查数据格式、字段权限和业务规则
                  </p>
                </div>
                
                <div className="space-y-2">
                  <div className="flex justify-between text-sm">
                    <span>验证进度</span>
                    <span>{uploadProgress}%</span>
                  </div>
                  <Progress value={uploadProgress} className="w-full" />
                </div>

                <div className="flex justify-center mt-4">
                  <Button variant="outline" onClick={handleCancel} disabled={loading}>
                    取消验证
                  </Button>
                </div>
              </CardContent>
            </Card>
          )}

          {/* 验证结果步骤 */}
          {currentStep === 'results' && importResult && (
            <div className="space-y-6">
              {/* 验证汇总 */}
              <Card>
                <CardHeader>
                  <CardTitle className="flex items-center gap-2">
                    {importResult.success ? (
                      <CheckCircle className="h-5 w-5 text-green-500" />
                    ) : (
                      <XCircle className="h-5 w-5 text-red-500" />
                    )}
                    验证结果汇总
                  </CardTitle>
                </CardHeader>
                <CardContent>
                  <div className={`grid gap-4 mb-4 ${importResult.skippedRows > 0 ? 'grid-cols-4' : 'grid-cols-3'}`}>
                    <div className="text-center">
                      <div className="text-2xl font-bold text-blue-600">
                        {importResult.totalRows}
                      </div>
                      <div className="text-sm text-gray-500">总记录数</div>
                    </div>
                    <div className="text-center">
                      <div className="text-2xl font-bold text-green-600">
                        {importResult.successRows}
                      </div>
                      <div className="text-sm text-gray-500">验证通过</div>
                    </div>
                    <div className="text-center">
                      <div className="text-2xl font-bold text-red-600">
                        {importResult.errorRows}
                      </div>
                      <div className="text-sm text-gray-500">验证失败</div>
                    </div>
                    {importResult.skippedRows > 0 && (
                      <div className="text-center">
                        <div className="text-2xl font-bold text-orange-600">
                          {importResult.skippedRows}
                        </div>
                        <div className="text-sm text-gray-500">无效行跳过</div>
                      </div>
                    )}
                  </div>

                  {/* 错误汇总 */}
                  {importResult.summary.duplicateObjectNumbers.length > 0 && (
                    <Alert className="mb-4">
                      <AlertTriangle className="h-4 w-4" />
                      <AlertDescription>
                        发现重复的对象编号: {importResult.summary.duplicateObjectNumbers.join(', ')}
                      </AlertDescription>
                    </Alert>
                  )}

                  {/* 跳过行汇总 */}
                  {importResult.skippedRows > 0 && (
                    <Alert className="mb-4">
                      <Info className="h-4 w-4" />
                      <AlertDescription>
                        已自动跳过 {importResult.skippedRows} 条无效行（只有设备类有数据的空行）
                      </AlertDescription>
                    </Alert>
                  )}
                </CardContent>
              </Card>

              {/* 详细验证结果 */}
              <Card>
                <CardHeader>
                  <CardTitle>详细验证结果</CardTitle>
                </CardHeader>
                <CardContent>
                  <Tabs defaultValue="errors" className="w-full">
                    <TabsList className="grid w-full grid-cols-3">
                      <TabsTrigger value="errors">
                        错误记录 ({importResult.records.filter(r => r.errors.length > 0).length})
                      </TabsTrigger>
                      <TabsTrigger value="warnings">
                        警告记录 ({importResult.records.filter(r => r.warnings.length > 0).length})
                      </TabsTrigger>
                      <TabsTrigger value="success">
                        成功记录 ({importResult.records.filter(r => r.errors.length === 0).length})
                      </TabsTrigger>
                    </TabsList>

                    <TabsContent value="errors" className="space-y-2 max-h-60 overflow-auto">
                      {importResult.records
                        .filter(r => r.errors.length > 0)
                        .map((record, index) => (
                          <div key={index} className="border rounded p-3">
                            <div className="flex items-center justify-between mb-2">
                              <span className="font-medium">{record.objectNumber}</span>
                              <Badge variant="destructive">错误</Badge>
                            </div>
                            <ul className="text-sm text-red-600 space-y-1">
                              {record.errors.map((error, i) => (
                                <li key={i}>• {error}</li>
                              ))}
                            </ul>
                          </div>
                        ))}
                    </TabsContent>

                    <TabsContent value="warnings" className="space-y-2 max-h-60 overflow-auto">
                      {importResult.records
                        .filter(r => r.warnings.length > 0)
                        .map((record, index) => (
                          <div key={index} className="border rounded p-3">
                            <div className="flex items-center justify-between mb-2">
                              <span className="font-medium">{record.objectNumber}</span>
                              <Badge variant="secondary">警告</Badge>
                            </div>
                            <ul className="text-sm text-orange-600 space-y-1">
                              {record.warnings.map((warning, i) => (
                                <li key={i}>• {warning}</li>
                              ))}
                            </ul>
                          </div>
                        ))}
                    </TabsContent>

                    <TabsContent value="success" className="space-y-2 max-h-60 overflow-auto">
                      {importResult.records
                        .filter(r => r.errors.length === 0)
                        .map((record, index) => (
                          <div key={index} className="border rounded p-3">
                            <div className="flex items-center justify-between">
                              <div>
                                <span className="font-medium">{record.objectNumber}</span>
                                <span className="text-sm text-gray-500 ml-2">
                                  {record.objectDescription}
                                </span>
                              </div>
                              <Badge variant="default">通过验证</Badge>
                            </div>
                          </div>
                        ))}
                    </TabsContent>
                  </Tabs>
                </CardContent>
              </Card>

              {/* 选择导入方式 */}
              <Card>
                <CardHeader>
                  <CardTitle>选择导入方式</CardTitle>
                </CardHeader>
                <CardContent className="space-y-4">
                  {validationChoices.map((choice) => (
                    <Button
                      key={choice.action}
                      variant="outline"
                      className="w-full p-4 h-auto justify-start"
                      onClick={() => handleImportChoice(choice.action)}
                      disabled={loading}
                    >
                      <div className="text-left">
                        <div className="font-medium">{choice.label}</div>
                        <div className="text-sm text-gray-500 mt-1">
                          {choice.description}
                        </div>
                      </div>
                    </Button>
                  ))}

                  <div className="flex justify-center mt-4 pt-4 border-t">
                    <Button variant="outline" onClick={handleCancel}>
                      <X className="h-4 w-4 mr-2" />
                      取消导入
                    </Button>
                  </div>
                </CardContent>
              </Card>
            </div>
          )}

          {/* 导入成功步骤 */}
          {currentStep === 'success' && importResult && (
            <Card>
              <CardHeader>
                <CardTitle className="flex items-center gap-2 text-green-600">
                  <CheckCircle className="h-5 w-5" />
                  数据导入完成
                </CardTitle>
              </CardHeader>
              <CardContent className="space-y-4">
                <div className="text-center">
                  <div className="text-4xl font-bold text-green-600 mb-2">
                    {importResult.successRows}
                  </div>
                  <p className="text-lg font-medium">条记录成功导入</p>
                  <p className="text-sm text-gray-500 mt-2">
                    数据已添加到 {specialty} → {objectCategory} 下
                  </p>
                </div>

                <Alert>
                  <CheckCircle className="h-4 w-4" />
                  <AlertDescription>
                    设备实例已自动创建，属性表数据已分配到命名信息表、位置信息表和基础参数表。
                    您可以在专业导航栏中查看导入的设备实例。
                  </AlertDescription>
                </Alert>

                <div className="flex gap-3">
                  <Button onClick={() => handleOpenChange(false)} className="flex-1">
                    完成
                  </Button>
                  <Button variant="outline" onClick={resetDialog}>
                    继续导入
                  </Button>
                </div>
              </CardContent>
            </Card>
          )}
        </div>
      </DialogContent>
    </Dialog>
  );
}